/* Testing the Bezier functions */
/* Andy Lynch */

int ptsize = 4;
int circleRadius = 10;
color startColor = color( 255, 0, 0);
color endColor = color( 255, 255, 255);

float[] pty = new float[ ptsize];
float[] ptx = new float[ ptsize];
int bs = 3;
int bover = -1;
boolean locked = false;
float bdifx = 0.0; 
float bdify = 0.0; 
boolean drawpoints = true;
boolean drawlines = true;
int maxSteps = 20;

void setup() 
{
  size(400, 400); 
  noStroke();
//  colorMode(RGB, 255, 255, 255, 100);
  rectMode( RADIUS);

  ptx[ 0] = 85;
  pty[ 0] = 20;
  ptx[ 1] = 10;
  pty[ 1] = 10;
  ptx[ 2] = 90;
  pty[ 2] = 90;
  ptx[ 3] = 15;
  pty[ 3] = 80;
}

void draw() 
{   
  color eColor;
  background( 204);
  stroke( 128, 128, 128);
  fill( 128, 128, 128);
  if( drawlines){
    line( ptx[ 0], pty[ 0], ptx[ 1], pty[ 1]);
    line( ptx[ 2], pty[ 2], ptx[ 3], pty[ 3]);
  }
  bover = -1;
  for(int i = 0; i < 4; i++){
    if (mouseX > ptx[ i]-bs && mouseX < ptx[ i]+bs && 
        mouseY > pty[ i]-bs && mouseY < pty[ i]+bs) {
      bover = i;  
      if(!locked) { 
        stroke(255); 
        fill(153);
      } 
    } else {
      stroke(153);
      fill(153);
    }
    rect( ptx[ i], pty[ i], bs, bs);
  };
  noFill();
  stroke( 0, 0, 0);
  if( drawlines){
    bezier( ptx[ 0], pty[ 0], ptx[ 1], pty[ 1], ptx[ 2], pty[ 2], ptx[ 3], pty[ 3]);
  }
  if( drawpoints){
    fill(255);
    int steps = maxSteps;
    for (int i = 0; i < steps + 1; i++) {
      float t = i / float(steps);
      eColor = lerpColor( startColor, endColor, i / float(steps));
      fill( eColor);
      float x = bezierPoint( ptx[ 0], ptx[ 1], ptx[ 2], ptx[ 3], t);
      float y = bezierPoint( pty[ 0], pty[ 1], pty[ 2], pty[ 3], t);
      ellipse(x, y, circleRadius, circleRadius);
    }
  }
}

void keyPressed() {
  if ( key == ' ') {
    drawpoints = !drawpoints;
  }
  if ( key == 'l') {
    drawlines = !drawlines;
  }
}

void mousePressed() {
  if(bover > -1) { 
    locked = true; 
    fill(255, 255, 255);
    bdifx = mouseX-ptx[ bover]; 
    bdify = mouseY-pty[ bover]; 
  } else {
    locked = false;
  }

}

void mouseDragged() {
  if(locked) {
    ptx[ bover] = mouseX-bdifx; 
    pty[ bover] = mouseY-bdify; 
  }
}

void mouseReleased() {
  locked = false;
}

